import React from 'react';
import moment from 'moment';
import { Button, Dropdown, Menu, Popconfirm, Tooltip } from 'antd';
import {
  createFromIconfontCN,
  DeleteOutlined,
  EyeInvisibleOutlined,
  EyeOutlined,
  FormOutlined,
  MoreOutlined,
} from '@/utils/antdIcons';

const MyIcon = createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_2829840_yn99z7n48rr.js',
});

const TIME_96 = Array.from({ length: 96 }, (__, i) => {
  /** 96点位: 0015 ~ 2400 */
  let hh = Math.floor(i / 4);
  let mm = ((i + 1) % 4) * 15;
  if (mm === 0) {
    hh += 1;
    mm = '00';
  }
  return `${hh.toString().padStart(2, '0')}${mm}`;
});

const TIME_24 = Array.from({ length: 24 }, (__, i) => {
  /** 24点位: 0100 ~ 2400 */
  const hh = `${i + 1}`.padStart(2, '0');
  const mm = '00';
  return `${hh}${mm}`;
});

const getTimeNames = (latitude, startDate, endDate) => {
  // 根据时间范围、维度获取列名称
  if (latitude === 'stack96') {
    return [...TIME_96];
  }
  if (latitude === 'stack24') {
    return [...TIME_24];
  }
  const _diffType = latitude === 'month' ? 'months' : 'days';
  const _list = Array.from(
    { length: moment(endDate).diff(moment(startDate), _diffType) + 1 },
    (__, i) =>
      moment(startDate)
        .add(i, _diffType)
        .format(latitude === 'month' ? 'MM' : 'MMDD'),
  );
  if (latitude === 'month' || latitude === 'day') {
    return _list;
  }
  if (latitude === '96' || latitude === '24') {
    const hmList = latitude === '96' ? TIME_96 : TIME_24;
    return _list.map((x) => hmList.map((t) => `${x} ${t}`)).flat();
  }
};

export const getColumns = ({ buttonPermissions, form, handleEdit, counterPartyList }) => {
  if (!form) return;
  const { latitude, startDate, endDate } = form;
  if (!latitude || !startDate || !endDate) return;

  const renderFn = (v) => {
    if (typeof v !== 'number' || isNaN(v)) return '-';
    const numInt = Math.round(v);
    return numInt >= 0 ? numInt : <span style={{ color: '#FF3131' }}>{Math.abs(numInt)}</span>;
  };

  // 高亮 > 当前时间
  let diffIdx;
  if (latitude === '96' || latitude === '24') {
    const _space = latitude === '96' ? 15 : 60;
    const diffMinutes = moment().diff(moment(startDate), 'minutes');
    diffIdx = Math.floor(diffMinutes / _space);
  }
  const timeColumns = getTimeNames(latitude, startDate, endDate).map((name, i) => {
    let temp = {
      code: name,
      name: name,
      align: 'center',
      render: renderFn,
    };
    if (i < diffIdx) {
      temp.getCellProps = () => {
        let style = {};
        style['--bgcolor'] = '#454C57';
        style.color = '#929292';
        return { style };
      };
    }
    return temp;
  });

  /** 跳转（todo: 参数加密） */
  const jumpFn = (f, r) => {
    if (!f || !r) return;
    let lati = f.latitude;
    if (lati === 'month' || lati === 'day') lati = 'stack96';
    const q = {
      f1: f.provinceName,
      f2: r.category,
      f3: f.counterpartyTitle,
      st: f.startDate,
      en: f.endDate,
      p: f.provinceId,
      s: r.id,
      c: f.counterpartyList.join(','),
      r: f.radixType,
      l: lati,
    };
    const uriSearch = Object.entries(q)
      .map(([k, v]) => `${k}=${encodeURIComponent(v)}`)
      .join('&');
    window.open(`${location.href}?${uriSearch}`);
  };

  /** 交互 */
  const renderCateGory = (v, r) => {
    const { t } = r;
    if (!t) return v;
    if (t === 'total') {
      return (
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <MyIcon type={r.icon} style={{ fontSize: 16, marginRight: 8, color: r?.color }} />
          <div>{v}</div>
        </div>
      );
    }
    return (
      <div
        style={{
          display: 'flex',
          width: '100%',
          alignItems: 'center',
          justifyContent: 'space-between',
        }}
      >
        <div
          style={{
            width: 115,
            overflow: 'hidden',
            whiteSpace: 'nowrap',
            textOverflow: 'ellipsis',
          }}
        >
          <Tooltip placement="topLeft" title={v}>
            {v}
          </Tooltip>
        </div>
        {t === 'jump' && (
          <Button
            type="link"
            icon={<MyIcon type="icon-cangguan" style={{ fontSize: 14 }} />}
            onClick={(e) => {
              e.stopPropagation();
              jumpFn(form, r);
            }}
          />
        )}
        {t === 'edit' && (
          <div onClick={(e) => e.stopPropagation()}>
            <Dropdown
              overlay={() => (
                <Menu
                  onClick={async (e) => {
                    const { key, domEvent } = e;
                    domEvent.isPropagationStopped();
                    if (key === 'edit') {
                      await handleEdit(r, counterPartyList);
                      // editDataMadal(r, buttonPermissions, form);
                    }
                  }}
                >
                  <Menu.Item key="edit" icon={<FormOutlined style={{ color: '#1E7CE8' }} />}>
                    编辑
                  </Menu.Item>
                  {/* r.contractType === 'custom' && */}
                  {
                    <Menu.Item key="show">
                      <Popconfirm
                        title={r.calculate === '1' ? '确认隐藏合约?' : '确认显示合约？'}
                        onConfirm={(e) => {
                          e.stopPropagation();
                          // onPartake(r, form);
                        }}
                        okText="是"
                        cancelText="否"
                      >
                        {r.calculate === '1' ? <EyeInvisibleOutlined /> : <EyeOutlined />}
                        {r.calculate === '1' ? '隐藏' : '显示'}
                      </Popconfirm>
                    </Menu.Item>
                  }
                  {/* r.contractType === 'custom' && */}
                  {/* delStationContracts */}
                  {
                    <Menu.Item key="delete">
                      <Popconfirm
                        title="确认删除合约?"
                        onConfirm={(e) => {
                          e.stopPropagation();
                          // onDeleteData(r, form);
                        }}
                        okText="是"
                        cancelText="否"
                      >
                        <DeleteOutlined style={{ color: '#EB5757' }} />
                        删除
                      </Popconfirm>
                    </Menu.Item>
                  }
                </Menu>
              )}
            >
              <MoreOutlined style={{ fontSize: 14 }} />
            </Dropdown>
          </div>
        )}
      </div>
    );
  };

  return [
    {
      code: 'category',
      name: '',
      width: 150,
      lock: true,
      render: renderCateGory,
      getCellProps: () => ({ style: { borderRight: '1px solid #727272' } }),
    },
    {
      code: 'total',
      name: '汇总',
      width: 65,
      lock: true,
      align: 'center',
      render: renderFn,
      getCellProps: () => ({ style: { borderRight: '1px solid #727272' } }),
    },
    ...timeColumns,
  ];
};
